<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\command;

use app\common\model\book\Category;
use app\common\model\book\Book as BookModel;
use app\common\model\book\Chapter as ChapterModel;
use app\common\model\book\BookExtra as BookExtraModel;
use app\common\model\pull\Pull as PullModel;
use app\common\model\pull\PullLog as PullLogModel;
use app\common\service\ContentService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;


class UpdateThirdStatus extends Command
{
    protected function configure()
    {
        $this->setName('update_third_status')
            ->setDescription('拉取书籍数据');
    }
    protected function execute(Input $input, Output $output)
    {
        try {
            $pull = PullModel::where("online","=",1)->where("id","=",1)->select();

            if($pull){
                foreach ($pull as $k=>$v){
                    $spiderid = $v["id"];
                    $bookArr = BookModel::where("siteid","=",$spiderid)->column('sourceid');
                    //日志文件
                    $logfile = '';
                    //1.查询第三方所有授权书籍
                    $book_list = $this->get_book_list($v,$logfile);
                    if($book_list){
                        foreach ($book_list as $bk=>$bv){
                            //判断是否已经拉取过书籍
                            if (in_array($bv["sourceid"], $bookArr)){
                                $bookinfo  =BookModel::where("siteid","=",$spiderid)->where("sourceid","=",$bv["sourceid"])->findOrEmpty();
                                if (!$bookinfo->isEmpty()){
                                    echo date('Y-m-d H:i:s')."ID:".$bookinfo->id."BookName:".$bookinfo->book_name."匹配书籍成功".'-----'.$bv["sourceid"].PHP_EOL;
                                    if($bookinfo->third_status!=5){
                                        $third_status = ($bv['third_status']==1)?1:4;
                                        if ($third_status!=$bookinfo->third_status){
                                            BookModel::where("id","=",$bookinfo->id)->update(['third_status'=>$third_status]);
                                            echo date('Y-m-d H:i:s')."ID:".$bookinfo->id."BookName:".$bookinfo->book_name."书籍修改成功".'-----'.$bv["sourceid"].PHP_EOL;
                                        }else{
                                            echo date('Y-m-d H:i:s')."ID:".$bookinfo->id."BookName:".$bookinfo->book_name."状态无需修改".'-----'.$bv["sourceid"].PHP_EOL;
                                        }
                                    }else{
                                        echo date('Y-m-d H:i:s')."ID:".$bookinfo->id."BookName:".$bookinfo->book_name."状态无需修改".'-----'.$bv["sourceid"].PHP_EOL;
                                    }
                                    echo date('Y-m-d H:i:s')."ID:".$bookinfo->id."BookName:".$bookinfo->book_name."书籍修改结束".'-----'.$bv["sourceid"].PHP_EOL;
                                }
                            }

                        }
                    }
                }
            }
        } catch (\Exception $e) {
            Log::write('修改书籍状态完成:' . $e->getMessage());
            return false;
        }
    }

    private function formatQueryString($params,$appKey,$appSecret){
        $params['req_time'] = time().str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $params['app_secret'] = $appSecret;
        $params['access_token'] = $this->getAccessToken($params);
        $params['app_key'] = (int)$appKey;
        unset($params['app_secret']);
        $queryString = http_build_query($params);
        return $queryString;
    }
    function getAccessToken($params) {
        // 排除键值是app_key、app_token的参数数据

        // 按ASCII排序
        ksort($params);

        // 重置指针
        reset($params);

        // 组装成键值对的字符串格式
        $queryString = '';
        foreach ($params as $key => $value) {
            $queryString .= $key . '=' . $value . '&';
        }
        // 添加app_secret
        $queryString = rtrim($queryString, '&');
        // md5加密
        $accessToken = md5($queryString);

        return $accessToken;
    }

    public function get_book_list($pull,$logfile) {

        if(strpos($pull["booklist_url"],"http://")===false){
            echo date('Y-m-d H:i:s')."小说列表数据为空 渠道ID :".$pull['id'].PHP_EOL;
            return false;
        }else{
            if($pull['id']==1){
                $bookListDataArr = [];
                for ($i = 1; $i < 1000; $i++) {
                    $queryString = $this->formatQueryString(['page'=>$i],$pull["app_key"],$pull["app_secret"]);
                    $url = $pull["booklist_url"].'?'.$queryString;
                    $bookListData = json_decode(file_get_contents($url),true);
                    if(is_array($bookListData['result']['data'])){
                        $bookListDataArr[] = $bookListData['result']['data'];
                    }

                    if (count($bookListData['result']['data']) < 200||is_array($bookListData['result']['data'])==false) {
                        break; // 当数据小于200时跳出循环
                    }
                }
                if($bookListDataArr && is_array($bookListDataArr)) {
                    $data = array();
                    foreach ($bookListDataArr as $kk=>$vv){
                        foreach ($vv as $k=>$v){
                            if (isset($v["category_info"]['site'])&&isset($v["category_info"]['bid'])){
                                $data[] = [
                                    "sourceid"=>$v["book_id"]??null,
                                    "book_name"=>$v["book_title"]??null,
                                    "siteid"=>$v["channel_id"]??null,
                                    "author"=>$v["author_name"]??null,
                                    "third_status"=>$v["is_online"]??0,
                                    "keyword"=>$v["plotlabel"]??null,
                                    "word_count"=>$v["word_count"]??null,
                                    "chapter_count"=>$v["chapter_count"]??null,
                                    "fullflag"=>$v["writing_process"]??null,
                                    "channel_type"=>$v["category_info"]['site']??null,
                                    "sort_id"=>$v["category_info"]['bid']??null,
                                ];
                            }
                        }
                    }
                    return $data;
                }else{
                    echo date('Y-m-d H:i:s')."小说列表数据为空".PHP_EOL;
                }
            }else{
                    echo date('Y-m-d H:i:s')."小说列表数据为空".PHP_EOL;
            }
        }
    }

}